///////////////////////////////////////////////////////////////////////////////
//
// Licensed under the MIT License
//
// Copyright (c) 2010 Chris Colinsky
// All Rights Reserved
//
// version	0.5
// http://code.google.com/p/sugarcookie/
// http://code.google.com/p/sugarcookie/wiki/License
//
////////////////////////////////////////////////////////////////////////////////

package sugarcookie.ui {
	import flash.display.Sprite;
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;
	
	import sugarcookie.commands.ICommand;
	import sugarcookie.display.SpriteBase;

	public class BasicButton extends SpriteBase implements IUIButton {
		protected var _command:ICommand;
		protected var _active:Boolean = true;
		protected var _activeArea:Sprite;
		
		public function BasicButton(props:Object=null) {
			super(props);
			internal_init();
		}
		
		public function set active(value:Boolean):void {
			_active = value;
			toggleHandlers(value);
			refresh();
		}
		
		public function get active():Boolean {
			return _active;
		}
		
		public function set command(value:ICommand):void {
			_command = value;
		}
		
		public function toggle():void {
			
		}
		
		protected function refresh():void {
			
		}
		
		protected function internal_init():void {
			mouseChildren = false;
			toggleHandlers(true);
		}
		
		protected function toggleHandlers(active:Boolean,listenee:EventDispatcher=null,events:Array=null):void {
			if (events==null) events = [{event:MouseEvent.CLICK,handler:internal_click},{event:MouseEvent.MOUSE_OVER,handler:internal_mouseover},{event:MouseEvent.MOUSE_OUT,handler:internal_mouseout}];
			if (listenee==null) listenee = this;
			buttonMode = active;
			
			var i:int;
			if (active) for (i=0;i<events.length;i++) listenee.addEventListener(events[i].event,events[i].handler);
			else for (i=0;i<events.length;i++) listenee.removeEventListener(events[i].event,events[i].handler);
		}
		
		private function internal_click(evt:MouseEvent):void {
			if (!active) return;
			click(evt);
			if (_command!=null) _command.execute();
		}
		
		protected function click(evt:MouseEvent):void {
			
		}
		
		private function internal_mouseover(evt:MouseEvent):void {
			if (!active) return;
			mouseover(evt);
		}
		
		protected function mouseover(evt:MouseEvent):void {
			
		}
		
		private function internal_mouseout(evt:MouseEvent):void {
			if (!active) return;
			mouseout(evt);
		}
		
		protected function mouseout(evt:MouseEvent):void {
			
		}
		
		protected function createActiveArea(xPos:Number=0,yPos:Number=0,hitWidth:Number=0,hitHeight:Number=0,useAsHitArea:Boolean=true):void {
			_activeArea = new Sprite();
			_activeArea.graphics.beginFill(0xFF0000,0);
			_activeArea.graphics.drawRect(xPos,yPos,hitWidth==0?width:hitWidth,hitHeight==0?height:hitHeight);
			_activeArea.graphics.endFill();
			addChildAt(_activeArea,0);
			if (useAsHitArea) {
				_activeArea.mouseEnabled = false;
				hitArea = _activeArea;
			}
		}
	}
}